<script setup>
import { reactive, ref, nextTick, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import AddI18n from '@/components/AddI18n.vue'
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { logoutApi } from '@/api/login'
import { createI18nItem,importI18nItem } from '@/api/I18n'

const route = useRoute()
const router = useRouter()
const showModal = ref(false)
const currentTitle = ref('新闻池')

// 获取登录用户信息
const logindata = ref(null)

// 在组件挂载时获取登录信息
onMounted(() => {
  const loginInfo = localStorage.getItem('login')
  if (loginInfo) {
    const parsedInfo = JSON.parse(loginInfo)
    logindata.value = parsedInfo.info
    console.log(logindata._rawValue)
  }
})

const handlelogout = () => {
  logoutApi().then((res) => {
    localStorage.removeItem('login')
    router.replace('/login')
    console.log(res)
  })
}

// 路由名称与标题的映射
const titleMap = {
  '/pool': '新闻池',
  '/published': '新闻发布',
  '/release': '已发布新闻',
  '/sistem': '系统管理',
  '/log': '日志管理',
  '/message': '消息管理',
  '/i18': '国际化管理',
}

// 监听路由变化，更新标题
watch(
  () => route.path,
  (newPath) => {
    currentTitle.value = titleMap[newPath] || '新闻池'
  },
  { immediate: true },
)

const handleModalConfirm = (formData) => {
  // 将表单数据传递给createI18nItem
  createI18nItem(formData)
    .then((res) => {
      // 这里可以添加成功后的处理逻辑，比如刷新列表
      showModal.value = false
    })
    .catch((err) => {
      console.error('创建国际化项失败:', err)
    })
}

//国际化导入功能
const handleImport = () => {
  // 创建一个隐藏的文件输入元素
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.json,.csv' // 支持Excel、JSON和CSV文件
  
  // 当用户选择文件后触发
  fileInput.onchange = (event) => {
    const file = event.target.files[0]
    if (!file) return
    
    // 创建FormData对象并添加文件
    const formData = new FormData()
    formData.append('file', file)
    
    // 根据文件扩展名自动识别格式
    let format = undefined;
    const fileName = file.name.toLowerCase();
    if (fileName.endsWith('.json')) {
      format = 'json';
    } else if (fileName.endsWith('.csv')) {
      format = 'csv';
    }
    
    // 调用导入API，传递自动识别的格式
    importI18nItem(formData, format)
      .then((res) => {
        console.log('导入成功', res)
        // 这里可以添加成功后的处理逻辑，比如刷新列表
      })
      .catch((err) => {
        console.error('导入失败', err)
      })
  }
  
  // 触发文件选择对话框
  fileInput.click()
}

</script>

<template>
  <div class="common-layout">
    <header class="header">
      <img src="../../assets/logo.png" alt="" />
      <span>战略微头条</span>
      <div class="user-menu">
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <img :src="'http://localhost:3000' + logindata?.avatar" alt="" />
            <!-- <span>{{ logindata?.username }}</span> -->
            <span>𓏸 𓂂 𓈒 🐟</span>
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>个人中心</el-dropdown-item>
              <el-dropdown-item>个人设置</el-dropdown-item>
              <el-dropdown-item @click="handlelogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <img src="../../assets/语言切换.svg" alt="" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>简体中文</el-dropdown-item>
              <el-dropdown-item>English</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
    <div class="container">
      <aside class="sidebar">
        <nav class="menu">
          <div class="menu-item">
            <router-link to="/pool">新闻池</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/published">新闻发布</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/release">已发布新闻</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/sistem">系统管理</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/log">日志管理</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/message">通知管理</router-link>
          </div>
          <div class="menu-item">
            <router-link to="/i18">国际化管理</router-link>
          </div>
        </nav>
      </aside>
      <div class="content-wrapper">
        <div class="content-header">
          {{ currentTitle }}
          <div v-if="route.path === '/published'" class="flex items-center">
            <img src="../../assets/播放.svg" class="w-5 h-5" />
            <button class="preview-btn" @click="router.push('/preview')">预览</button>
          </div>
          <div v-if="route.path === '/i18'" class="flex items-center">
            <a
              href="http://localhost:3000/i18n/export?format=csv&languageTags=zh-CN,en-US&download=true&filename=i18n-data"
              class="mr-2 w-18 h-7 text-[12px] flex items-center justify-center shadow-sm bg-white border border-gray-200"
            >
              导出
            </a>
            <button
              class="mr-2 w-18 h-7 text-[12px] flex items-center justify-center shadow-sm bg-white border border-gray-200"
              @click="handleImport"
              >
              导入
            </button>
            <button
              class="mr-2 w-18 h-7 text-[12px] text-white bg-blue-400 flex items-center justify-center"
              @click="showModal = true"
            >
              + 新建
            </button>
            <img src="../../assets/刷新.svg" class="w-5 h-5 mr-2" />
            <img src="../../assets/排序.svg" class="w-5 h-5 mr-2" />
            <img src="../../assets//设置.svg" class="w-h h-5" />
          </div>
        </div>
        <main class="main">
          <div style="background-color: #ffffff">
            <router-view></router-view>
          </div>
        </main>
      </div>
    </div>
    <AddI18n v-model:visible="showModal" @confirm="handleModalConfirm" />
  </div>
</template>

<style scoped>
.common-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
}

.header {
  width: 100%;
  height: 60px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e6e6e6;
}

.header img {
  width: 100px;
  height: 40px;
  margin-right: 10px;
  vertical-align: middle;
}

.header span {
  font-size: 20px;
  font-weight: 700;
  margin-left: 30px;
}

.container {
  display: flex;
  width: 100%;
  height: 800px;
}

.sidebar {
  min-width: 300px;
}

.menu {
  padding: 6px 0;
}

.menu-item {
  height: 56px;
  line-height: 56px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item a {
  display: block;
  text-decoration: none;
  color: #303133;
  font-size: 16px;
  padding: 0 20px;
}

.menu-item a.router-link-exact-active {
  color: #409eff;
  border-right: 3px solid #409eff;
  background-color: #e6f7ff;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-header {
  width: 1500px;
  height: 64px;
  line-height: 64px;
  padding: 0 20px;
  background-color: #fff;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-btn {
  border: none;
  cursor: pointer;
  font-size: 14px;
}

.main {
  flex: 1;
  padding: 15px;
  background-color: #eef1f4;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.main > div {
  width: 100%;
  flex: 1;
  box-sizing: border-box;
  overflow: auto;
}

.user-menu {
  margin-left: auto;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-right: 30px;
}

.el-dropdown-link img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

button {
  cursor: pointer;
}
</style>
